package com.dlc.shop.security.common.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.dlc.shop.common.constants.OauthCacheNames;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.CacheManagerUtil;
import com.dlc.shop.common.util.RedisUtil;
import com.dlc.shop.security.common.bo.LoginInfoBO;
import com.dlc.shop.security.common.bo.UidInfoBO;
import com.dlc.shop.security.common.enums.SocialType;
import com.dlc.shop.security.common.manager.TokenStore;
import com.dlc.shop.security.common.service.AppConnectService;
import com.dlc.shop.security.common.util.AuthUserContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author FrozenWatermelon
 * @date 2020/6/30
 */
@RestController
@Tag(name = "注销")
@AllArgsConstructor
public class LogoutController {

    private final TokenStore tokenStore;
    private final AppConnectService appConnectService;
    private final CacheManagerUtil cacheManagerUtil;


    @PostMapping("/logOut")
    @Operation(summary = "退出登陆" , description = "点击退出登陆，清除token，清除菜单缓存")
    public ServerResponseEntity<Void> logOut(HttpServletRequest request) {
        String accessToken = request.getHeader("Authorization");
        if (StrUtil.isBlank(accessToken)) {
            return ServerResponseEntity.success();
        }
        // 获取用户信息
        UidInfoBO uidInfo = AuthUserContext.getUidInfo(tokenStore.getUidByToken(accessToken));
        // 只有微信公众号和小程序的登录会进行登录并绑定的操作
        if (Objects.equals(uidInfo.getSysType(), SysTypeEnum.ORDINARY)) {
            LoginInfoBO loginInfoBO = tokenStore.getLoginInfoByCache();
            if (loginInfoBO != null && Objects.equals(loginInfoBO.getSocialType(), SocialType.MA.value()) || Objects.equals(loginInfoBO.getSocialType(),SocialType.MP.value())) {
                // 解除绑定的用户
                appConnectService.unBindUser(loginInfoBO.getBizUserId(), loginInfoBO.getSocialType());
                // 移除loginInfo的缓存
                RedisUtil.del(OauthCacheNames.LOGIN_INFO + accessToken);
            }
        }
        // 退出登录，清理权限的缓存
        if (Objects.equals(uidInfo.getSysType(), SysTypeEnum.MULTISHOP)) {
            cacheManagerUtil.evictCache("ShopPermissions", uidInfo.getUserId());
        }
        // 退出登录，清理权限的缓存
        if (Objects.equals(uidInfo.getSysType(), SysTypeEnum.PLATFORM)) {
            cacheManagerUtil.evictCache("SysPermissions", uidInfo.getUserId());
        }
        // 退出登录
        StpUtil.logoutByTokenValue(accessToken);
        return ServerResponseEntity.success();
    }

}
